import _ from 'lodash';
import { query, create, update, changeState } from '../services/task';

const mainProps = [
  'name', 'id', 'packageSize', 'price', 'guide',
];

export default {
  namespace: 'task',
  state: {
    tasks: [],
    keys: [],
  },
  effects: {
    *query(state, { put }) {
      const result = yield query();
      const tasks = _.get(result, 'tasks');
      let keys = [];
      tasks.forEach((task) => {
        const item = _.cloneDeep(task);
        keys = _.union(keys, Object.keys(item));
      });
      // 求出所有的属性的并集
      yield put({
        type: 'save',
        payload: {
          tasks,
          keys,
        },
      });
    },
    *create({ payload: { value, onEnd } }) {
      try {
        delete value.id;
        const data = yield create();
        const { id } = data;
        // 处理value,把非MainProps的属性全部放到settings中
        const settings = {};
        const main = {};
        Object.keys(value).forEach((key) => {
          if (mainProps.indexOf(key) >= 0) {
            main[key] = value[key];
          } else {
            settings[key] = value[key];
          }
        });
        yield update({
          id,
          settings,
          ...main,
        });
      } catch (e) {
        return onEnd(e.message || JSON.stringify(e));
      }

      onEnd();
    },
    *edit({ payload: { value, onEnd } }) {
      try {
        const settings = {};
        const main = {};
        delete value.state;
        Object.keys(value).forEach((key) => {
          if (mainProps.indexOf(key) >= 0) {
            main[key] = value[key];
          } else {
            settings[key] = value[key];
          }
        });
        yield update({
          settings,
          ...main,
        });
      } catch (e) {
        return onEnd(e.message || JSON.stringify(e));
      }
      onEnd();
    },
    *changeState({ payload: { state, id } }, { put }) {
      yield changeState({
        state, id,
      });
      yield put({
        type: 'query',
      });
    },
  },
  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },
};

